//
//  WmcBrandLibraryVC.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/6/9.
//

import MJRefresh
import UIKit

// MARK: - 扩展WmcBrandLibraryVC + WmcNavigatorProtocol

extension WmcBrandLibraryVC: WmcNavigatorProtocol {
    static func navigationPaths() -> [WmcNavigatorManager.Path] {
        return [.brandLibrary]
    }

    static func willMakeNavigationVC(with parms: WmcNavigatorManager.Parms) -> UIViewController {
        var vm = WmcBrandLibraryVM()
        if let viewModel = parms.context as? WmcBrandLibraryVM {
            vm = viewModel
        }
        let vc = WmcBrandLibraryVC(vm)
        return vc
    }
}

// MARK: - 扩展WmcBrandLibraryVC + WmcVMProtocol

extension WmcBrandLibraryVC: WmcVMProtocol {
    typealias VMType = WmcBrandLibraryVM
}

// MARK: - [WmcBrandLibraryVC]

class WmcBrandLibraryVC: WmcBaseVC {
    // Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()

        title = "品牌库"
        viewModel.refreshData()
    }

    // Internal

    lazy var searchBar: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()

    lazy var searchView: WmcSearchView = {
        let view = WmcSearchView(placeholderText: "输入名称查找品牌图片",
                                 font: 14.wmc_font)
        return view
    }()

    lazy var lineView: UIView = {
        let view = UIView()
        view.backgroundColor = .wmc_grayH19_F5F5F5
        return view
    }()

    lazy var headerLabel: UILabel = {
        let label = UILabel.YP.Create(text: "点击选中品牌图片",
                                      font: 18.yp.uiFont(weight: .bold),
                                      color: UIColor.wmc_grayH2_323233,
                                      alignment: .left)
        return label
    }()

    lazy var layout: UICollectionViewFlowLayout = {
        let layout = UICollectionViewFlowLayout
            .YP.CreateGridLayout(scrollDirection: .vertical,
                                 minimumLineSpacing: 8,
                                 minimumInteritemSpacing: 8,
                                 sectionInset: Wmc_standardEdge.yp.set(bottom:0))
        return layout
    }()

    lazy var collectionView: UICollectionView = {
        let collectionView = UICollectionView
            .YP.Create(layout: layout,
                       delegate: self,
                       dataSource: self,
                       registers: [
                           YPRegister(WmcBrandLibraryCell.self),
                           YPRegister(WmcBrandLibraryFooterView.self, style: .footer),
                       ])
        return collectionView
    }()

    lazy var emptyView: WmcBrandLibraryEmptyView = {
        let view = WmcBrandLibraryEmptyView()
        view.isHidden = true
        return view
    }()

    lazy var badNetworkView: WmcBadNetworkEmptyView = {
        let view = WmcBadNetworkEmptyView()
        view.isHidden = true
        return view
    }()

    override func makeUI() {
        makeNavView(showShadow: false)

        addSubview(searchBar)
        searchBar.snp.makeConstraints { make in
            make.top.equalTo(navView.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(52)
        }

        searchBar.addSubview(searchView)
        searchView.snp.makeConstraints { make in
            make.top.equalTo(8)
            make.bottom.equalTo(-8)
            make.left.equalTo(Wmc_standardEdge.left)
            make.right.equalTo(-Wmc_standardEdge.left)
        }

        addSubview(lineView)
        lineView.snp.makeConstraints { make in
            make.top.equalTo(searchBar.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(8)
        }

        addSubview(headerLabel)
        headerLabel.snp.makeConstraints { make in
            make.top.equalTo(lineView.snp.bottom).offset(8)
            make.left.equalTo(Wmc_standardEdge.left)
            make.right.equalTo(Wmc_standardEdge.right)
            make.height.equalTo(22)
        }

        addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.top.equalTo(headerLabel.snp.bottom).offset(8)
            make.left.right.bottom.equalToSuperview()
        }

        addSubview(emptyView)
        emptyView.snp.makeConstraints { make in
            make.top.equalTo(headerLabel)
            make.left.right.bottom.equalTo(collectionView)
        }

        addSubview(badNetworkView)
        badNetworkView.snp.makeConstraints { make in
            make.edges.equalTo(emptyView)
        }

        // 初始判断网络
        setBadNetworkType(YPNetworkReachability.queryNetworkReachabilityType())
    }

    override func bindViewAction() {
        collectionView.mj_header = MJRefreshNormalHeader(refreshingBlock: { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.refreshData()
        })

        collectionView.mj_footer = MJRefreshBackNormalFooter(refreshingBlock: { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.loadMoreData()
        })

        // 搜索数据
        searchView.textDidChangeBlock = { [weak self] text in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.searchData(text)
        }

        // 坏网络刷新
        badNetworkView.refreshClosure = { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.refreshData()
        }
    }

    override func bindViewModel() {
        // 上拉下拉状态
        viewModel.bindRefreshState(to: collectionView)

        // 数据列表更新
        viewModel.listRelay.subscribe(onNext: { [weak self] value in
            guard let weakSelf = self else { return }
            if value.count > 0 {
                weakSelf.emptyView.isHidden = true
            } else {
                weakSelf.emptyView.isHidden = false
            }
            weakSelf.collectionView.reloadData()
        }).disposed(by: rx.disposeBag)

        
        // 监听网络状态
        YPNetworkReachability.monitoring().subscribe(onNext: { [weak self] type in
            guard let weakSelf = self else { return }
            weakSelf.setBadNetworkType(type)
        }).disposed(by: rx.disposeBag)
    }

    /// 设置网络状态占位视图
    func setBadNetworkType(_ type: YPNetworkReachabilityType) {
        switch type {
        case .unknow,
             .notReachable:
            badNetworkView.isHidden = false
        case .ethernetOrWiFi,
             .cellular:
            badNetworkView.isHidden = true
            viewModel.refreshData()
        }
    }
}

// MARK: - UICollectionViewDelegate

extension WmcBrandLibraryVC: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if let model = viewModel.listRelay.value.yp.object(at: indexPath.row) {
            viewModel.didSelectLogoBlock?(model)
            backAction()
        }
    }
}

// MARK: - UICollectionViewDelegateFlowLayout

extension WmcBrandLibraryVC: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        return CGSize(width: collectionView.frame.width, height: 64 + Wmc_safeAreaBottom)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let lineCount: CGFloat = 2
        let lineSpacing = self.layout.minimumLineSpacing * (lineCount - 1)
        let horizontalEdge = self.layout.sectionInset.yp.horizontal
        let width = (collectionView.frame.size.width - lineSpacing - horizontalEdge) / lineCount - 1
        let height = width * 0.8675
        return CGSize(width: width, height: height)
    }
}

// MARK: - UICollectionViewDataSource

extension WmcBrandLibraryVC: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionFooter {
            let footerView: WmcBrandLibraryFooterView = collectionView.yp.dequeueReusableView(.init(WmcBrandLibraryFooterView.self,
                                                                                                    style: .footer),
                                                                                              indexPath: indexPath)
            return footerView
        } else {
            return .init()
        }
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel.listRelay.value.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: WmcBrandLibraryCell = collectionView.yp.dequeueReusableCell(for: indexPath)
        if let model = viewModel.listRelay.value.yp.object(at: indexPath.row) {
            cell.configModel(model)
        }
        return cell
    }
}
